package com.example.user.newsongpaly;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.widget.RemoteViews;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class MyService extends Service {
    MyCellBack myCellBack = null;
    static MediaPlayer mp ;
    Timer timer;
    PlayerReceiver playerReceiver;
    private static final int REQUEST_CODE = 0;
    public static final String ACTION_PLAY = "play";
    public static final String ACTION_next = "next";
    public static final String ACTION_previous = "previous";
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    class MyBinder extends Binder{
        public MyService getmyService(){
            return MyService.this;
        }
    }

    @Override
    public void onCreate() {
         mp = new MediaPlayer();
        playerReceiver = new PlayerReceiver();
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ACTION_PLAY);
        mFilter.addAction(ACTION_next);
        mFilter.addAction(ACTION_previous);
        registerReceiver(playerReceiver, mFilter);
        super.onCreate();
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String url = intent.getStringExtra("Url");
        int se = intent.getIntExtra("kaishi",0);//（1 控制开始暂停，0 播放音乐）
        if (se==1) {
            if (mp.isPlaying()) {
                mp.pause();
                timer.cancel();
            }else {
                mp.start();
                setTimer();
            }
        }else{if (mp!=null){
                try {
                    if (mp.isPlaying()){
                        mp.stop();//停止播放
                        mp = new MediaPlayer();
                        mp.setDataSource(url);
                        mp.prepareAsync();//加载
                        mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(MediaPlayer mediaPlayer) { //加载回调
                                mp.start();//开始播放
                            }
                        });
                    }else {
                        mp.stop();
                        mp = new MediaPlayer();
                        mp.setDataSource(url);//设置路径
                        mp.prepareAsync();//加载
                        mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { //加载回调
                            @Override
                            public void onPrepared(MediaPlayer mediaPlayer) {
                                mp.start();//开始播放
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            setTimer();
            show();
        }
        return START_NOT_STICKY;
    }

    public void setTimer(){
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            int NowTime = mp.getCurrentPosition();
            if (NowTime!=0){
                Log.i("NowTimessssss", String.valueOf(NowTime));
                int longtime = mp.getDuration();
                if (myCellBack!=null){
                    myCellBack.CurrentPosition(NowTime,longtime);
                    Log.i("sdf","1111111");
                }
                Log.i("sdf","asdf");
            }
        }
    },0,100);
}
    public MyCellBack getMyCellBack(){
        return this.myCellBack;
    }
    public void setMyCellBack(MyCellBack myCellBack){
        this.myCellBack = myCellBack;
    }

    public interface MyCellBack{
        void CurrentPosition(int time,int longtime);
    }
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void show(){

        RemoteViews remoteViews = new RemoteViews(this.getPackageName(),R.layout.tongzhi);
        Notification.Builder  builder = new Notification.Builder(this.getApplicationContext()).setContent(remoteViews);
        builder.setWhen(System.currentTimeMillis()).setSmallIcon(R.mipmap.star);
        Notification notification = builder.build();
        notification.defaults = Notification.DEFAULT_SOUND;
        Intent intentPlay = new Intent(ACTION_PLAY);// 指定操作意图--设置对应的行为ACTION
        PendingIntent pIntentPlay = PendingIntent.getBroadcast(this, REQUEST_CODE, intentPlay, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.start1,pIntentPlay);
        Intent intentPlay2 = new Intent(ACTION_next);// 指定操作意图--设置对应的行为ACTION
        PendingIntent pIntentPlay2 = PendingIntent.getBroadcast(this, REQUEST_CODE, intentPlay2, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.Next,pIntentPlay2);
        Intent intentPlay3 = new Intent(ACTION_previous);// 指定操作意图--设置对应的行为ACTION
        PendingIntent pIntentPlay3 = PendingIntent.getBroadcast(this, REQUEST_CODE, intentPlay3, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.Previous,pIntentPlay3);
        startForeground(110, notification);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void play(){
        if (mp!=null){
            try {
                if (mp.isPlaying()){
                    mp.stop();//停止播放
                    mp = new MediaPlayer();
                    mp.setDataSource(ListContentlist.getlistContentlist().getContentlistBean().getM4a());
                    mp.prepareAsync();//加载
                    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mediaPlayer) { //加载回调
                            mp.start();//开始播放
                        }
                    });
                }else {
                    mp.stop();
                    mp = new MediaPlayer();
                    mp.setDataSource(ListContentlist.getlistContentlist().getContentlistBean().getM4a());//设置路径
                    mp.prepareAsync();//加载
                    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { //加载回调
                        @Override
                        public void onPrepared(MediaPlayer mediaPlayer) {
                            mp.start();//开始播放
                        }
                    });
                }
                setTimer();
                show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public class PlayerReceiver extends BroadcastReceiver{

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(ACTION_PLAY)){
                if (mp.isPlaying()){
                    Log.i("ddddddd","dddddd5");
                    mp.pause();
                }else {
                    mp.start();
                    Log.i("ddddddd","dddddd5");
                }
            }if (action.equals(ACTION_next)){
                Log.i("ddddddd","dddddd6");
                ListContentlist.getlistContentlist().setJiaitem();
                play();
            }if (action.equals(ACTION_previous)){
                Log.i("ddddddd","dddddd7");
            }
        }
    }
}
